package com.itheima.springboottlias.filter;

import com.itheima.springboottlias.Util.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;

import java.io.IOException;
@Slf4j
//@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //统一的乱码处理 敏感数据处理  字符编码处理 权限验证  登录验证。。。。。。
        //1.获取请求路径
        String requestURL = request.getRequestURL().toString();

        //2.判断是否是登录请求（是否放行）
        //如果是直接放行
        if (requestURL.contains("/login")){
            log.info("登录请求 直接放行");
            filterChain.doFilter(request,response);
            return;//注意return不能省略
        }

        //3.获取请求头中的token
        //没token 拦截请求，封装错误结果
        String jwt = request.getHeader("token");
        if (jwt == null){
            //没用携带token 拦截请求封装错误结果
            log.info("请求头没有token 拦截请求");
            response.setStatus(401);
            //response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;//注意return不能省略
        }

        //4.解析token判断token是否正确
        //解析错误或者不正确拦截请求，封装错误结果
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            //解析失败
            //携带的token有误，封装错误结果
            log.info("解析token失败 拦截请求");
            response.setStatus(401);
//          response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;//注意return不能省略
        }

        //5.放行
        log.info("放行");
        filterChain.doFilter(servletRequest,servletResponse);
    }
}
